package cn.qu.netty.boot;

import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import java.nio.charset.Charset;

import com.alibaba.fastjson.JSONObject;

import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.FullHttpRequest;

public class PostParameterResolver extends AbstractParameterResolver {

	@Override
	public Object[] resolve(FullHttpRequest req, HandlerMapping handlerMapping) throws ParameterResolverException {
		Object[] paramArr = super.resolve(req, handlerMapping);
		try {

			ByteBuf buf = req.content();
			String paramStr = buf.toString(Charset.defaultCharset());
			Parameter pojoParam = handlerMapping.getPojoParam();
			if (pojoParam == null) {
				return paramArr;
			}

			Object pojoParamValue = JSONObject.parseObject(paramStr, pojoParam.getType());
			Object[] objectArr = new Object[paramArr.length + 1];
			if (paramArr.length > 0) {
				Field indexField = pojoParam.getClass().getDeclaredField("index");
				indexField.setAccessible(true);
				int index = (int) indexField.get(pojoParam);
				for (int i = 0; i < objectArr.length; i++) {
					if (i == index) {
						objectArr[i] = pojoParamValue;
					} else if (i < index) {
						objectArr[i] = paramArr[i];
					} else if (i > index) {
						objectArr[i] = paramArr[i - 1];
					}
				}
			} else {
				objectArr[0] = pojoParamValue;
			}

			return objectArr;
		} catch (Exception e) {
			throw new ParameterResolverException(e);
		}
	}
}
